<?php

namespace app\admin\controller;

use app\common\model\ConfigPubModel;
use app\common\model\GuessReportModel;
use app\common\model\GuessTopUserLogModel;
use app\common\model\TalentListConfModel;
use app\common\model\UserModel;
use think\Db;

class GuessTopController extends BaseController
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $model = GuessReportModel::field('*');
            if (ctype_digit($years = $this->get('years'))) {
                $model = $model->where('years', $years);
            }
            return json([
                'count' => $model->count(),
                'list' => $model->order('weeks', 'desc')
                    ->page((int)$this->get('page', 1), (int)$this->get('limit', 20))
                    ->select()->each(function ($query) {
                        $explode = explode('-', $query->weeks);
                        $dates = getWeekDate($explode[0], $explode[1]);
                        $query->weeks_string = str_replace('-', ' 年 第 ', $query->weeks);
                        $query->weeks_string = $query->weeks_string . ' 周 ( ' . date('Y-m-d', strtotime($dates[0])) . ' - ' . date('Y-m-d', strtotime($dates[1])) . ' )';
                        if ($query->total_sales) {
                            $query->total_sales = bcdiv($query->total_sales, '100', 2);
                        }

                        if ($query->total_reward) {
                            $query->total_reward = bcdiv($query->total_reward, '100', 2);
                        }

                        if ($query->average_reward) {
                            $query->average_reward = bcdiv($query->average_reward, '100', 2);
                        }
                    })
                    ->toArray(),
                'code' => 0,
            ]);
        }
        $date = date('Y');
        return $this->assign([
            'date' => [$date, $date - 1, $date - 2, $date - 3]
        ])->fetch();
    }

    public function info()
    {
        if (!$id = $this->get('id', '')) {
            return static::bulidFail('传参错误');
        }

        if (!$explode = explode('-', $id)) {
            return static::bulidFail('传参错误');
        }

        if (count($explode) !== 2) {
            return static::bulidFail('传参错误');
        }

        if ($this->request->isAjax()) {
            $where = " 1=1 ";

            if (ctype_digit($use_id = $this->get('uid'))) {
                $where = $where . "and uid={$use_id} ";
            } elseif ($nick_name = trim($this->get('nick_name', ''))) {
                if ($uids = UserModel::whereLike('nick_name', $nick_name . '%')->column('id')) {
                    $where = $where . "and uid in(" . implode(',', $uids) . ") ";
                }
            }

            $page = (int)$this->get('page', 1);
            $limit = (int)$this->get('limit', 20);

            $number = ($page - 1) * $limit;

            $dates = getWeekDate($explode[0], $explode[1]);
            $where = $where . "and update_time BETWEEN '{$dates[0]}' and '{$dates[1]}'";
            $sql = "SELECT uid,sum(profit-amount) as profit FROM db_guess_order where {$where} AND status in(2, 3) GROUP BY `uid` order by profit desc LIMIT {$number},$limit";

            $list = Db::query($sql);

            $nick_names = UserModel::field('nick_name,id')
                ->whereIn('id', array_column($list, 'uid'))
                ->column('nick_name', 'id');
            $logs = GuessTopUserLogModel::where('weeks', $id)->column(null, 'uid');

            foreach ($list as &$value) {
                $number++;
                $value['number'] = $number;
                if ($value['profit']) {
                    $value['profit'] = bcdiv($value['profit'], '100', 2);
                    if (!empty($logs[$value['uid']])) {
                        $value = array_merge($value,
                            [
                                'top_status' => $logs[$value['uid']]['status'],
                                'ranking' => $logs[$value['uid']]['ranking'],
                                'remark' => $logs[$value['uid']]['remark'],
                                'operator' => $logs[$value['uid']]['operator'],
                            ]
                        );
                    } else {
                        $value = array_merge($value, ['top_status' => 0, 'ranking' => 0, 'remark' => '', 'operator' => '']);
                    }
                }
                $value['nick_name'] = $nick_names[$value['uid']];
            }

            return json([
                'count' => Db::query("SELECT count(*) as count FROM (SELECT uid FROM db_guess_order where {$where} AND status in(2, 3) GROUP BY `uid`) a")[0]['count'] ?? 0,
                'list' => $list,
                'code' => 0,
            ]);
        }

        return $this->assign(['id' => $id])->fetch();
    }

    public function edit()
    {
        if (!ctype_digit($uid = $this->get('uid'))) {
            return static::bulidFail('参数错误');
        }

        if (!$weeks = trim($this->get('weeks', ''))) {
            return static::bulidFail('参数错误');
        }

        if (!$user = UserModel::field('nick_name')->where('id', $uid)->find()) {
            return static::bulidFail('参与用户不存在');
        }

        if ($this->request->isAjax()) {
            if (!ctype_digit($ranking = $this->post('ranking'))) {
                return static::bulidFail('排名错误');
            }

            if (!in_array($status = $this->post('status'), ['0', '1'])) {
                return static::bulidFail('奖品状态错误');
            }

            if (!$model = GuessTopUserLogModel::where('weeks', $weeks)->where('uid', $uid)->find()) {
                $model = new GuessTopUserLogModel();
            }

            $model->uid = $uid;
            $model->weeks = $weeks;
            $model->ranking = $ranking;
            $model->status = $status;
            $model->remark = trim($this->post('remark', ''));
            $model->operator = $this->admin_name;

            if (!$model->save()) {
                return static::bulidFail('编辑失败');
            }

            return static::bulidSuccess([], '编辑成功');
        }

        if (!$model = GuessTopUserLogModel::where('weeks', $weeks)->where('uid', $uid)->find()) {
            $model = new \stdClass();
            $model->ranking = '';
            $model->status = 0;
            $model->remark = '';
        }

        $model->nick_name = $user->nick_name;

        return $this->assign([
            'uid' => $uid,
            'weeks' => $weeks,
            'profit' => $this->get('profit', '0.00'),
            'model' => $model
        ])->fetch();
    }

    public function conf()
    {
        if ($this->request->isAjax()) {
            if ($content = trim($this->post('content', ''))) {
                if (!$model = TalentListConfModel::field('content,operator')->where('id', 3)->find()) {
                    $model = new TalentListConfModel();
                    $model->id = 3;
                    $model->title = '竞猜达人榜';
                    $model->create_time = time();
                }
                $model->content = addslashes($content);
                $model->operator = $this->admin_name;
                if ($model->save()) {
                    $this->addAdminLog('修改了竞猜达人榜配置');
                    return static::bulidSuccess([], '编辑成功');
                }
            }

            return static::bulidFail('编辑失败');
        }

        return $this->assign([
            'content' => stripslashes(TalentListConfModel::where('id', 3)->value('content') ?: '')
        ])->fetch();
    }
}